package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrdersTask {
    @Autowired
    private OrdersMapper ordersMapper;
    @Scheduled(cron ="0 * * * * ?" )
    public void cancelOrders(){
        log.info("修改超时订单");
        //查询状态为1且超时的订单
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime time = now.plusMinutes(-15);
        List<Orders> list= ordersMapper.statusAndCreatime(Orders.PENDING_PAYMENT, time);
        //把该订单状态修改为6 并且设置取消原因 取消时间
        if (!CollectionUtils.isEmpty(list)){
            for (Orders orders : list) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(now);
                orders.setCancelReason("订单超时未支付");
                //更新数据
                ordersMapper.update(orders);
            }
        }

    }
    @Scheduled(cron = "0 0 1 * * ?  ")
    public void processDeliveryOrder(){
        log.info("修改派送中订单");
        List<Orders> list = ordersMapper.statusAndCreatime(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now());
        if (!CollectionUtils.isEmpty(list)){
            for (Orders orders : list) {
                orders.setStatus(Orders.COMPLETED);
                ordersMapper.update(orders);
            }
        }
    }
}
